package com.task.controller;


import com.github.pagehelper.PageInfo;
import com.task.entity.User;
import com.task.service.UserService;
import com.task.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户Controller
 * 
 * @author WangJie
 * @date 2022-11-27
 */
@RestController
@RequestMapping("/User")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

     //1.分页查询
    @GetMapping("/page")
    public PageVo getUserPageList(@RequestParam(required = false,defaultValue = "1")Integer pageNum,@RequestParam(required = false,defaultValue = "20")Integer pageSize){
        List<User> userList=userService.getUserPageList(pageNum,pageSize);
        PageVo pageVo = new PageVo();
        pageVo.setCode(HttpStatus.OK.value());
        pageVo.setList(userList);
        pageVo.setMsg("查询成功");
        pageVo.setTotal(new PageInfo(userList).getTotal());
        return pageVo;
    }

    //2.根据id批量查询并放入redis中
    @PostMapping("/idList")
    public List<User> getUserListByIdList(@RequestBody List<Integer> idList){
        List<User> userList=new ArrayList<>();
        userList= userService.listByIds(idList);
        if(!CollectionUtils.isEmpty(idList)){
            if(!CollectionUtils.isEmpty(userList)){
                Map<Integer, User> map = userList.stream().collect(Collectors.toMap(User::getId, a -> a, (k1, k2) -> k1));
                redisTemplate.opsForValue().multiSet(map);
            }
        }
        return userList;
    }

    //3.新增user + 事务
    @PostMapping("/save")
    @Transactional(propagation = Propagation.REQUIRED)
    public User saveUser(@RequestBody User user){
        User saveUser = this.saveUser(user);
        return saveUser;
    }

    //4.根据id删除user +事务
    @DeleteMapping("/delete")
    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(@RequestParam Integer id){
        if(id!=null){
            userService.removeById(id);
            redisTemplate.delete(id);
        }
    }
}
